package com.tricode.ile.training.task.mite;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class PrintRandomLinesFromFile {

    private static FileReader fileReader;
    private static BufferedReader bufferedReader;
    private static File file;
    private static Random rand;

    public static void main(String[] args) {
        try {
            checkArgNumbers(args);
            ArrayList<String> list = createListOfStringsFromFile(args[0]);
            printRandomLines(list, Integer.parseInt(args[1]));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    private static void printRandomLines(List<String> list, int linesToPrint) {
        if (list.size() < linesToPrint) {
            System.err.println("The file doesn't have that much lines. Try again.");
            System.exit(1);
        }
        while (linesToPrint != 0) {
            int idx = randInt(0, list.size() - 1);
            System.out.println("Printing line: " + idx + ". The line content is: " + list.get(idx).toString());
            linesToPrint--;
        }
    }

    private static ArrayList<String> createListOfStringsFromFile(String filePath) throws IOException {
        bufferedReader = new BufferedReader(new FileReader(filePath));
        file = new File(filePath);
        int numOfLines = (int) (file.length() / 45);
        ArrayList<String> lines = new ArrayList<String>(numOfLines);
        for (int i = 0; i < numOfLines; i++) {
            lines.add(i, bufferedReader.readLine());
        }
        return lines;
    }

    private static void checkArgNumbers(String[] args) {
        if (args.length != 2) {
            System.err.println("Invalid argument number.");
            System.exit(1);
        }
        if (args.length == 2) {
            System.out.println("Your arguments are ok. Proceeding with execution.");
        }
    }

    private static int randInt(int min, int max) {
        rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }
}
